package com.dms.modules.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.common.exception.BusinessException;
import com.dms.modules.product.entity.Product;
import com.dms.modules.product.entity.ProductFavorite;
import com.dms.modules.product.mapper.ProductFavoriteMapper;
import com.dms.modules.product.service.ProductFavoriteService;
import com.dms.modules.product.service.ProductService;
import com.dms.modules.product.vo.ProductVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品收藏服务实现类
 */
@Slf4j
@Service
public class ProductFavoriteServiceImpl extends ServiceImpl<ProductFavoriteMapper, ProductFavorite> implements ProductFavoriteService {

    @Autowired
    private ProductService productService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addFavorite(Long userId, Long productId) {
        // 参数校验
        if (userId == null || productId == null) {
            throw new BusinessException("参数不能为空");
        }

        // 检查商品是否存在
        Product product = productService.getById(productId);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }

        try {
            // 查询现有记录
            LambdaQueryWrapper<ProductFavorite> queryWrapper = new LambdaQueryWrapper<ProductFavorite>()
                    .eq(ProductFavorite::getUserId, userId)
                    .eq(ProductFavorite::getProductId, productId);

            ProductFavorite favorite = getOne(queryWrapper);
            
            LocalDateTime now = LocalDateTime.now();
            if (favorite != null) {
                // 如果记录存在且状态为已取消，则更新状态为已收藏
                if (favorite.getStatus() == 0) {
                    return lambdaUpdate()
                            .eq(ProductFavorite::getId, favorite.getId())
                            .set(ProductFavorite::getStatus, 1)
                            .set(ProductFavorite::getUpdateTime, now)
                            .update();
                }
                // 如果记录存在且状态为已收藏，直接返回true
                return true;
            }

            // 如果记录不存在，创建新记录
            favorite = new ProductFavorite();
            favorite.setUserId(userId);
            favorite.setProductId(productId);
            favorite.setStatus(1);
            favorite.setCreateTime(now);
            favorite.setUpdateTime(now);
            
            return save(favorite);
        } catch (Exception e) {
            log.error("添加收藏失败，userId={}, productId={}", userId, productId, e);
            throw new BusinessException("添加收藏失败，请稍后重试");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelFavorite(Long userId, Long productId) {
        if (userId == null || productId == null) {
            throw new BusinessException("参数错误");
        }

        try {
            return lambdaUpdate()
                    .eq(ProductFavorite::getUserId, userId)
                    .eq(ProductFavorite::getProductId, productId)
                    .eq(ProductFavorite::getStatus, 1)
                    .set(ProductFavorite::getStatus, 0)
                    .set(ProductFavorite::getUpdateTime, LocalDateTime.now())
                    .update();
        } catch (Exception e) {
            log.error("取消收藏失败，userId={}, productId={}", userId, productId, e);
            throw new BusinessException("取消收藏失败，请稍后重试");
        }
    }

    @Override
    public IPage<ProductFavorite> getUserFavorites(Long userId, Integer pageNum, Integer pageSize) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }

        Page<ProductFavorite> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ProductFavorite> wrapper = new LambdaQueryWrapper<ProductFavorite>()
                .eq(ProductFavorite::getUserId, userId)
                .eq(ProductFavorite::getStatus, 1)  // 只查询已收藏的记录
                .orderByDesc(ProductFavorite::getCreateTime);

        return page(page, wrapper);
    }

    @Override
    public boolean isFavorite(Long userId, Long productId) {
        if (userId == null || productId == null) {
            return false;
        }

        return lambdaQuery()
                .eq(ProductFavorite::getUserId, userId)
                .eq(ProductFavorite::getProductId, productId)
                .eq(ProductFavorite::getStatus, 1)
                .exists();
    }

    @Override
    public Integer getFavoriteCount(Long productId) {
        if (productId == null) {
            return 0;
        }

        return lambdaQuery()
                .eq(ProductFavorite::getProductId, productId)
                .eq(ProductFavorite::getStatus, 1)
                .count()
                .intValue();
    }

    @Override
    public IPage<ProductVO> getUserFavoriteProducts(Long userId, Integer pageNum, Integer pageSize) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }

        // 获取收藏记录
        Page<ProductFavorite> favoritePage = new Page<>(pageNum, pageSize);
        IPage<ProductFavorite> favoriteIPage = lambdaQuery()
                .eq(ProductFavorite::getUserId, userId)
                .eq(ProductFavorite::getStatus, 1)
                .orderByDesc(ProductFavorite::getCreateTime)
                .page(favoritePage);
        
        // 转换为商品VO
        Page<ProductVO> resultPage = new Page<>(favoriteIPage.getCurrent(), favoriteIPage.getSize(), favoriteIPage.getTotal());
        List<ProductVO> productVOList = new ArrayList<>();
        
        for (ProductFavorite favorite : favoriteIPage.getRecords()) {
            Product product = productService.getById(favorite.getProductId());
            if (product != null) {
                ProductVO productVO = new ProductVO();
                BeanUtils.copyProperties(product, productVO);
                productVO.setFavorite(true)
                        .setFavoriteTime(favorite.getCreateTime());
                productVOList.add(productVO);
            }
        }
        
        resultPage.setRecords(productVOList);
        return resultPage;
    }
} 